package com.baidu.bulls.stock.trade.oauth.service;

import com.baidu.bulls.stock.common.utils.GlobalConstants;
import com.baidu.bulls.stock.entity.user.TradeUser;
import com.baidu.bulls.stock.trade.oauth.bo.OAuthTradeUser;
import com.baidu.bulls.stock.trade.oauth.repository.TradeUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


@Service("authStockUserDetailService")
public class AuthStockUserDetailServiceImpl implements UserDetailsService  {

    /**
     * 用户的数据层接口
     */
    @Autowired
    private TradeUserRepository tradeUserRepository;


    /**
     * 缓存管理接口
     */
    @Autowired
    private CacheManager cacheManager;


    /**
     * 根据用户账号获取用户对象接口
     * @param userNo
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userNo) throws UsernameNotFoundException {
       //先从缓存查找，有的话直接返回
        Cache cache = cacheManager.getCache(GlobalConstants.OAUTH_KEY_STOCK_USER_DETAILS);
        if (cache != null && cache.get(userNo) != null){
            return (UserDetails) cache.get(userNo).get();
        }
        //没有从数据库中查找
        TradeUser byUserNo = tradeUserRepository.findByUserNo(userNo);
        if (byUserNo == null){
            throw new UsernameNotFoundException(userNo + "no valid");
        }
        //对用户做封装处理
        UserDetails userDetails = new OAuthTradeUser(byUserNo);
        //封装的用户加入缓存返回给前端
        cache.put(userNo,userDetails);
        return userDetails;
    }



}
